<!-- 加油充值产品购买 -->
<template>
  <view class="bigbox">
    <!-- <LoadingOverlay
      v-model="loadingStatus"
      :text="loadingText"
      :size="60"
      color="#ff6c18"
    /> -->
    <view class="topbox">
      <view class="btbox">
        <view class="btwz">{{ oilInfo.stationName }}</view>
        <!-- <view class="kuai" style="margin: 20rpx 0">24小时营业</view> -->
        <view class="txbox" style="margin: 20rpx 0">
          <view class="jgwz">
            <text style="font-size: 38rpx; font-weight: 700"
              >￥{{ oilPriceDiscountUnit }}/L</text
            >
            <text style="font-size: 20rpx; margin-left: 10rpx">起</text>
          </view>
          <view @click="gotoAddress()">
            <van-icon name="guide-o" color="#fd6135" size="15px" />距您{{
              oilInfo.distance
            }}</view
          >
        </view>
        <view>地址： {{ oilInfo.address }}</view>
      </view>
      <view class="smallbox">
        <view class="bt">选择油号</view>
        <view class="tips">请先选择油号，再选择油枪。</view>
        <view class="nr">
          <view class="kuai">
            油号
            <u-dropdown
              inactive-color="#ff6c18"
              active-color="#2979ff"
              height="100"
            >
              <u-dropdown-item
                :title="oliWz"
                v-model="oliId"
                :options="oilList"
                @change="handleOliChange"
                :height="500"
              ></u-dropdown-item>
            </u-dropdown>
          </view>
          <view class="kuai">
            <view @click="handleOilGunDropdownClick">油枪</view>
            <u-dropdown
              inactive-color="#ff6c18"
              active-color="#2979ff"
              @click="handleOilGunDropdownClick"
            >
              <u-dropdown-item
                :disabled="isOilGunDisabled"
                :title="oliGunWz"
                v-model="oliGunId"
                :options="oliGunList"
                @change="handleOliGunChange"
                @click="handleOilGunDropdownClick"
                :height="500"
              ></u-dropdown-item>
            </u-dropdown>
          </view>
        </view>
      </view>
      <view class="smallbox">
        <view class="bt">充值面额</view>
        <view class="tips">最低100元起充,请选选择油枪号和油号再输入金额.</view>
        <view class="nr2  " >
          <view class="recharge">
            <view
              style="
                background-color: #f6f7f9;
                margin-bottom: 20rpx;
                padding: 20rpx;
                width: 800rpx;
                margin-right: 20rpx;
              "
              class="txbox"
            >
              <u-input
                :disabled="disabledInput"
                style="width:100%;"
                placeholder="选油号油枪,输入金额"
                v-model="money"
                type="digit"
              ></u-input>
              <u-icon
                v-if="money"
                name="close"
                size="20"
                @click="clearMoneyInput"
                style="margin: 0 10rpx; color: #999"
              ></u-icon>
              <view style="font-size: 28rpx; color: #999999">
                <text style="margin: 0 10rpx">约</text>
                {{ goodsPriceInfo.totalLitre }} L
              </view>
            </view>
            <u-button  
            type="primary"
            :disabled="disabledInput && money"
            @click="handleMoneyChange(money)"
            >确定</u-button
          >
          </view>

          <view class="nr3">
            <view
              class="jqbox"
              v-for="(ele2, index) in moneyList"
              :key="index"
              :class="activeIndex == index ? 'activejq' : ''"
              @click="handleClickJq(index)"
            >
              <view
                style="margin: 10rpx 0; font-size: 28rpx; font-weight: bold"
              >
                ￥{{ ele2.jg }}
              </view>
              <view class="text" v-if="ele2.highestScoreMoney"
                >立减￥{{ ele2.highestScoreMoney }}</view
              >
              <text class="icon2" v-if="ele2.highestScoreMoney>0">优惠</text>
              <view v-if="activeIndex == index" class="tbbox">
                <u-image
                  src="./static/xztb.png"
                  width="36rpx"
                  height="36rpx"
                ></u-image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="footerbox" v-if="showSettle">
      <view class="txbox">
        <view class="jgwz"
          >可用 {{ flqTicket }}
          <!-- {{ enumAll.SHOPMODEL[orderInfo.shopMode] }} -->
          复来券，商品抵扣
        </view>
        <view class="jgwz">
          - ￥
          <text class="price2">{{ goodsPriceInfo.highestScoreMoney }}</text>
          <!-- <u-input
            style="width: 100rpx"
            :height="'10rpx'"
            :border="true"
            class="inputBox"
            v-input-decimal
            placeholder="请输入抵扣的金额"
            type="digit"
            v-model="discountInput"
            @blur="handleDkInput"
          /> -->
        </view>
      </view>
      <view class="txbox" style="margin-bottom: 20rpx; height: 45rpx">
        <view>服务费</view>
        <view class="jgwz">+￥{{ goodsPriceInfo.handleFee }}</view>
      </view>
      <view class="txbox txbox2">
        <view class="kuai">
          <text style="font-size: 28rpx">合计：</text>
          <text class="jgwz price1" v-if="goodsPriceInfo.orderAmount"
            >￥{{ goodsPriceInfo.total }}</text
          >
          <text jgwz v-else>计算中...</text>
        </view>
        <view class="kuai">
          <u-button
            type="primary"
            size="default"
            :loading="loadingStatus"
            loadingText="计价中"
            @click="handleGoBuy"
            >立即购买</u-button
          >
        </view>
      </view>
    </view>
  </view>
  <!-- 地图弹出框 -->
  <van-popup
    v-model:show="showMap"
    round
    position="bottom"
    :style="{ height: '30%' }"
  >
    <view class="mapbox">
      <van-button class="btn" @click="openGMap" type="default"
        >高德地图</van-button
      >
      <van-button class="btn" @click="openBMap" type="default"
        >百度地图</van-button
      >
      <van-button class="btn" @click="openTMap" type="default"
        >腾讯地图</van-button
      >
      <van-button class="btn" @click="copyMap" type="default"
        >复制地址</van-button
      >
      <van-button class="btn btn2" type="default" @click="showMap = false"
        >取消</van-button
      >
    </view>
  </van-popup>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { enumAll, moneyApi, orderApi, userApi } from '@/api'
import { useOilStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store'
// 引入工具类
import { formatDistance } from '@/utils'
import { moneyUtils } from '@/utils/money'
import { browserVersion } from '@/utils/common'
import { debounce } from 'lodash'
//组件
import LoadingOverlay from '@/components/hy-loadingPage/index.vue'
// 初始数据
const userStore = useUserStore()
const { accessToken, useShareCode } = storeToRefs(userStore)
const oilStore = useOilStore()
const isApp = ref(false)
const loadingStatus = ref(false)
const oilPriceDiscountUnit = ref(null)
const contactNumber = ref()
const oilInfo = ref<any>(computed(() => oilStore.goodsOil))
const active = ref(0)
const money = ref()
const stationPrice = ref()
const stationName = ref()
//地图展示
const showMap = ref(false)
// 结算展示
const showSettle = ref(false)
const clickObj = ref({
  latitude: 0,
  longitude: 0,
  name: '',
  address: ''
})
const oliGunId = ref()
const oliGunWz = ref('')
const oliGunList = ref([
  { label: '5号', value: 0 },
  { label: '6号', value: 1 },
  { label: '8号', value: 2 }
])
const oliId = ref()
const oliWz = ref('')
const moneyList = ref<any>([
  { jg: '200', id: 1 },
  { jg: '300', id: 2 },
  { jg: '400', id: 3 },
  { jg: '500', id: 4 },
  { jg: '600', id: 5 },
  { jg: '800', id: 6 }
])
const goodsPriceInfo = ref<any>({
  totalLitre: 0,
  highestScoreMoney: 0,
  handleFee: 0,
  orderAmount: null,
  total: null
})
const activeIndex = ref(-1)
const flqTicket = ref()
const hlhyTicket = ref()
const clTicket = ref()

const oilList = computed(() => {
  return oilStore.goodsOilList.map((ele: any) => {
    return {
      label: ele.oilName,
      value: ele.oilId,
      stationPrice: ele.stationPrice,
      stationName: oilStore.goodsOil.stationName,
      oilGunNoList: ele.oilGunNoList.map((ele2: any) => {
        return {
          label: ele2,
          value: ele2
        }
      })
    }
  })
})

const handleOilGunDropdownClick = () => {
  if (!oliId.value) {
    uni.showToast({
      title: '请先选择油号',
      icon: 'none',
      mask: true
    })
  }
}
// 油枪变化
const handleOliGunChange = (e: any) => {
  // 再次检查是否选择了油号
  if (!oliId.value) {
    uni.showToast({
      title: '请先选择油号',
      icon: 'none',
      mask: true
    })
    // 重置选择
    // oliGunId.value = undefined
    oliGunWz.value = ''
    return
  }

  active.value = 1
  oliGunId.value = e
  const findObj = oliGunList.value.find((ele) => ele.value == e)
  if (findObj) {
    oliGunWz.value = findObj.label
  }
  if (money.value) {
    handleMoneyChange(money.value)
  }
}
// 油型变化
const handleOliChange = (e: any) => {
  oliId.value = e

  const findObj = oilList.value.find((ele) => ele.value == e)
  if (findObj) {
    oliWz.value = findObj.label
    oliGunList.value = findObj.oilGunNoList
  }

  console.log('油号', money.value)
  if (money.value) {
    handleMoneyChange(money.value)
  }
}

// #region ****************************** 购买流程  ******************************************/
// 金额选择
const handleClickJq = (index: number) => {
  if (disabledInput.value)
    return uni.showToast({
      title: '请先选择油枪',
      icon: 'none',
      mask: true
    })
  activeIndex.value = index
  money.value = moneyList.value[index].jg
  handleMoneyChange(money.value)
}
// 判断油枪是否禁用
const isOilGunDisabled = computed(() => {
  return !oliId.value
})
// 输入框是否禁用
const disabledInput = computed(() => {
  if (oliId.value && oliGunId.value) {
    return false
  } else {
    return true
  }
})
// 清除输入框
const clearMoneyInput = () => {
  showSettle.value = false
  money.value = ''
  activeIndex.value = -1
  // 重置相关数据
  goodsPriceInfo.value = {
    totalLitre: 0,
    highestScoreMoney: 0,
    handleFee: 0,
    orderAmount: null,
    total: null
  }
}

// 充值面额
const handleMoneyChange = async (price: any) => {
  // 验证并处理负数输入
  if (price < 100) {
    uni.showToast({
      title: '最低金额100元起充',
      icon: 'none',
      mask: true
    })
    money.value = 100
    price = 100
  }
  if (!price) {
    clearMoneyInput()
    return uni.showToast({
      title: '请输入充值金额',
      icon: 'none',
      mask: true
    })
  }
  const matchedIndex = moneyList.value.findIndex(
    (item: any) => item.jg == price
  )
  if (matchedIndex !== -1) {
    activeIndex.value = matchedIndex
  } else {
    activeIndex.value = -1 // 没有匹配项时取消激活状态
  }

  stationPrice.value = oilList.value.filter(
    (ele: any) => ele.value == oliId.value
  )[0].stationPrice
  stationName.value = oilList.value.filter(
    (ele: any) => ele.value == oliId.value
  )[0].stationName

  const { data } = await orderApi.oilCalculate({
    stationId: oilInfo.value.stationId,
    shopMode: 4,
    oilId: oliId.value,
    amounts: price,
    stationPrice: stationPrice.value,
    stationName: stationName.value,
    oilGunId: oliGunId.value
  })
  if (data && data.length == 1) {
    showSettle.value = true
    goodsPriceInfo.value = data[0]
    oilPriceDiscountUnit.value = data[0].oilPriceDiscountUnit
    const all = moneyUtils.subtract(
      goodsPriceInfo.value.orderAmount,
      goodsPriceInfo.value.highestScoreMoney
    )
    goodsPriceInfo.value.total = moneyUtils.addPrice(
      all,
      goodsPriceInfo.value.handleFee
    )
  }

  if (data && data.length > 0) {
    const updatedMoneyList = moneyList.value.map((ele: any) => {
      const foundItem = data.find((d: any) => d.orderAmount == ele.jg)
      if (foundItem) {
        return {
          ...ele,
          ...foundItem
        }
      }
      return ele
    })

    moneyList.value = updatedMoneyList
  } else {
    goodsPriceInfo.value = {}
    uni.showToast({
      title: '暂无数据',
      icon: 'none',
      mask: true
    })
  }
}

// 用户电话号码
const userPhone = async () => {
  const { data } = await userApi.userInfo()
  contactNumber.value = data.phone
}

// 创建订单
async function creatOrder() {
  loadingStatus.value = true
  const params = {
    orderProductSkus: [
      {
        count: 1,
        money: Number(money.value),
        shopProductSkuId: 99554,
        dynamicPric: true
      }
    ],
    orderMonies: [],
    integralsRuleId: 10,
    contactNumber: contactNumber.value,
    scoreMoney: goodsPriceInfo.value.highestScoreMoney,
    stationId: oilInfo.value.stationId,
    oilId: oliId.value,
    oilGun: oliGunId.value,
    liters: goodsPriceInfo.value.totalLitre,
    stationPrice: stationPrice.value,
    stationName: stationName.value
  }

  try {
    const { data } = await orderApi.orderAdd(params)

    if (data) {
      loadingStatus.value = false
      if (isApp.value) {
        const u = browserVersion()
        if (u.iPhone) {
          // @ts-ignore
          window.JSBridge.invoke('goPay', {
            orderId: data.id,
            money: data.payMoney
          })
          return
        } else if (u.isAndroid) {
          // @ts-ignore
          if (window?.Android) {
            // @ts-ignore
            window?.Android?.goPay(data.id, data.payMoney)
          }
          return
        }
      } else {
        location.href = `https://api.mylkjgs.com/?token=${accessToken.value}&orderId=${data.id}`
      }
    }
  } catch (err) {
    loadingStatus.value = false
    console.log(err)
  }
  uni.hideLoading()
}

// 购买
const handleGoBuy = debounce(
  async () => {
    await creatOrder()
  },
  3000,
  {
    leading: true, // 立即执行第一次点击
    trailing: false // 不在延迟结束后执行
  }
)

// #endregion
// #region ******************* 地图 ******************* /
const gotoAddress = () => {
  clickObj.value = {
    latitude: oilInfo.value.latitude,
    longitude: oilInfo.value.longitude,
    address: oilInfo.value.address,
    name: oilInfo.value.stationName
  }
  showMap.value = true
}

//高德
const openGMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&coordinate=gaode&callnative=0`
}
//百度
const openBMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `http://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${name}&output=html`
}
// 腾讯
const openTMap = () => {
  const { latitude, longitude, name } = clickObj.value
  window.location.href = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude};title=${name}`
}
// 复制地址
const copyMap = () => {
  const address = clickObj.value.address
    ? clickObj.value.address
    : '地址信息不可用' // 获取地址信息，若无则显示默认文本
  uni.setClipboardData({
    data: address,
    success: () => {
      showMap.value = false
      uni.showToast({
        title: '复制成功'
      })
    },
    fail: () => {
      showMap.value = false
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      })
    }
  })
}
// #endregion

// #region ******************* 优惠计算 ******************* /
const getDiscountTicket = async () => {
  try {
    // 复来券模式
    const { data } = await moneyApi.getMemberTotalFulaiquan()
    flqTicket.value = data
    hlhyTicket.value = 0
    clTicket.value = 0
  } catch (error: any) {
    console.log(error)
    uni.showToast({
      title: '获取优惠券失败' + error.msg,
      icon: 'none'
    })
    flqTicket.value = 0
    hlhyTicket.value = 0
    clTicket.value = 0
  }
}

// #endregion

// 初始页面
onLoad((option: any) => {
  if (option?.from?.toLowerCase?.() === 'app') {
    isApp.value = true
  }
  getDiscountTicket()
  oilPriceDiscountUnit.value = oilStore.goodsOil.minPrice
  userPhone()
  //  初始化油号
  handleOliChange(oilList.value[0].value)
  let moneys = moneyList.value.map((ele: any) => ele.jg).join(',')

  handleMoneyChange(moneys)
})
</script>
<style lang="scss" scoped>
.bigbox {
  font-size: 24rpx;
  background: linear-gradient(
    to bottom,
    #f9dcb8 5%,
    #faead7 25%,
    #f8f8f8 85%,
    #f5f5f5 100%
  );
  min-height: 100vh;
  .topbox {
    padding: 20rpx;
    padding-top: 40rpx;
    .btbox {
      background-color: white;
      border-radius: 10rpx;
      padding: 20rpx;
      margin-bottom: 40rpx;
      .kuai {
        width: 150rpx;
        height: 40rpx;
        line-height: 40rpx;
        border-radius: 5rpx;
        text-align: center;
        background-color: #fd6135;
        color: white;
      }
    }
    .smallbox {
      padding: 20rpx;
      margin-bottom: 40rpx;
      background-color: #fff;
      border-radius: 10rpx;
      .tips {
        margin: 20rpx 0;
        font-size: 26rpx;
        color: #ff6c18;
      }
      .bt {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
      }
      .nr {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .kuai {
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #f6f7f9;
          height: 100rpx;
          width: 48%;
          padding: 20rpx;
          border-radius: 10rpx;
        }
      }
      .nr3 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        margin-top: 30rpx;
        .jqbox {
          height: 120rpx;
          width: 30%;
          padding: 20rpx;
          background-color: #f6f7f9;
          padding: 20rpx;
          text-align: center;
          border: 1rpx solid #dbdbdb;
          margin-bottom: 20rpx;
          border-radius: 10rpx;
          position: relative;
          .text {
            font-size: 24rpx;
            color: #fe5644;
          }
          .icon2 {
            position: absolute;
            top: 0;
            left: 0;
            font-size: 18rpx;
            color: #fff;
            background-color: #fe5744;
            padding: 5rpx;
          }
          .yjbox {
            text-decoration: line-through;
          }
          .tbbox {
            position: absolute;
            right: -2rpx;
            bottom: -3rpx;
          }
        }
        .activejq {
          border: 3rpx solid #fe5744;
        }
      }
    }
  }
  .footerbox {
    width: 750rpx;
    padding: 20rpx;
    background: #ffffff;
    box-shadow: 0rpx -4rpx 16rpx 4rpx rgba(0, 0, 0, 0.1);
    position: fixed;
    bottom: 0rpx;

    .txbox {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10rpx;
    }
    .txbox2 {
      .kuai {
        width: 50%;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 35rpx;
        text-align: left;
        border-radius: 10rpx;
      }
    }
  }
}
.txbox {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
.btwz {
  font-weight: bold;
  font-size: 30rpx;
}
.hswz {
  color: #999;
  font-size: 24rpx;
}
.jgwz {
  color: #fe5644;
}
.price1 {
  font-size: 40rpx;
  font-weight: 700;
}
.price2 {
  font-size: 30rpx;
  font-weight: 700;
}

.mapbox {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f8fa;

  .btn {
    width: 100%;
    height: 80rpx;
    border: none;
    background-color: #fff;
  }

  .btn2 {
    margin-top: 20rpx;
  }
}

.active {
  color: #ff6c18 !important;
}
.recharge{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.u-dropdown__content__mask) {
  background-color: transparent;
}
</style>
